package com.example.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.pojo.PageData;
import com.example.pojo.ResultBean;
import com.example.pojo.SysUser;
import com.example.service.ISysUserService;
import com.example.vo.UserVo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lyj
 * @since 2023-02-15
 */
@RestController
@RequestMapping("/sys-user")
public class SysUserController {
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询全部
     * @return
     */
    @GetMapping("queryAll")
    public ResultBean queryAll() {
        return ResultBean.success(sysUserService.list());
    }

    /**
     * 切换头像
     * @param id
     * @param headPicture
     * @return
     */
    @GetMapping("/switchAvatar")
    public ResultBean switchAvatar(Long id, String headPicture) {
        //获取User对象
        SysUser user = sysUserService.getById(id);
        //修改头像地址
        user.setHeadPicture(headPicture);
        boolean rs = sysUserService.updateById(user);
        return rs ? ResultBean.success(user) : ResultBean.error();
    }

    /**
     * 分页条件查询
     * @param pageData
     * @param map
     * @return
     */
    @GetMapping("/list")
    public ResultBean list(PageData pageData, @RequestParam Map<String, Object> map) {
        map.forEach((k,v)-> System.out.println(k + ":" + v));
        Page<UserVo> page = new Page<>(pageData.getPageNum(),pageData.getPageSize());
        sysUserService.queryUserVoByCondition(page,map);
        return ResultBean.success(page);
    }

    /**
     * 新增或修改
     * @param sysUser
     * @return
     */
    @PostMapping("/saveOrUpdate")
    public ResultBean saveOrUpdate(@RequestBody SysUser sysUser){
        System.out.println("新增或修改的数据：" + sysUser);
        sysUser.setPassword(new Md5Hash(sysUser.getPassword(),sysUser.getUsername(),3).toString());
        boolean b = sysUserService.saveOrUpdate(sysUser);
        return b ? ResultBean.success() : ResultBean.error();
    }

    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    public ResultBean delete(@PathVariable("id") Long id){
        System.out.println("要删除的id" + id);
        boolean rs = sysUserService.removeById(id);
        return rs ? ResultBean.success() : ResultBean.error();
    }
}
